<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const connected = ref(false) // 连接状态
const form = reactive({
  host: 'broker.emqx.io',
  port: 1883,
  clientId: 'mqtt-client-' + Math.random().toString(16).slice(2),
  secure: false, // 是否启用SSL/TLS加密
  // TLS证书配置
  ca: '', // CA证书
  cert: '', // 客户端证书
  key: '', // 客户端私钥
  rejectUnauthorized: false // 是否验证服务器证书
})
let statusCheckInterval = null

// 切换加密模式
const toggleSecure = () => {
  if (form.secure) {
    // 启用SSL时，通常使用8883端口
    if (form.port === 1883) {
      form.port = 8883
    }
    ElMessage.success('已启用SSL/TLS加密，端口切换到8883')
  } else {
    // 禁用SSL时，通常使用1883端口
    if (form.port === 8883) {
      form.port = 1883
    }
    ElMessage.info('已禁用SSL/TLS加密，端口切换到1883')
  }
}

// 处理证书文件上传
const handleCertUpload = (type, event) => {
  const file = event.target.files[0]
  if (!file) return
  
  const reader = new FileReader()
  reader.onload = (e) => {
    form[type] = e.target.result
    ElMessage.success(`${type.toUpperCase()}证书已加载`)
  }
  reader.onerror = () => {
    ElMessage.error('证书文件读取失败')
  }
  reader.readAsText(file)
}

// 清除证书
const clearCert = (type) => {
  form[type] = ''
  ElMessage.info(`已清除${type.toUpperCase()}证书`)
}

// 检查证书配置状态
const getCertStatus = () => {
  const hasCA = !!form.ca
  const hasCert = !!form.cert
  const hasKey = !!form.key
  
  if (hasCA && hasCert && hasKey) {
    return { status: 'complete', text: '完整证书配置', type: 'success' }
  } else if (hasCA || hasCert || hasKey) {
    return { status: 'partial', text: '部分证书配置', type: 'warning' }
  } else {
    return { status: 'none', text: '无证书配置', type: 'info' }
  }
}




// 检查连接状态
const checkConnectionStatus = async () => {
  try {
    const { data } = await axios.get('/api/status')
    connected.value = data?.connected || false
  } catch (e) {
    connected.value = false
  }
}

// 启动状态检查
const startStatusCheck = () => {
  if (statusCheckInterval) return
  statusCheckInterval = setInterval(checkConnectionStatus, 2000) // 每2秒检查一次
}

// 停止状态检查
const stopStatusCheck = () => {
  if (statusCheckInterval) {
    clearInterval(statusCheckInterval)
    statusCheckInterval = null
  }
}

const connect = async () => {
  try {
    loading.value = true
    await axios.post('/api/connect', form)
    // 简单延时轮询确认
    for (let i = 0; i < 10; i++) {
      const { data } = await axios.get('/api/status')
      if (data?.connected) {
        ElMessage.success('连接成功')
        connected.value = true
        return
      }
      await new Promise(r => setTimeout(r, 700))
    }
    ElMessage.warning('已发起连接，稍后在状态栏确认')
  } catch (e) {
    ElMessage.error('连接失败: ' + (e?.response?.data?.message || e.message))
    connected.value = false
  } finally {
    loading.value = false
  }
}

const disconnect = async () => {
  try {
    await axios.post('/api/disconnect')
    ElMessage.success('已断开连接')
    connected.value = false
  } catch (e) {
    ElMessage.error('断开失败')
    connected.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  checkConnectionStatus() // 初始检查
  startStatusCheck() // 启动定期检查
})

onBeforeUnmount(() => {
  stopStatusCheck() // 清理定时器
})
</script>

<template>
  <div class="connection-page" style="overflow: visible;">
    <el-card shadow="never" class="connection-card">
      <template #header>
        <div class="card-header">
          <span>MQTT 连接配置</span>
          <el-tag :type="connected ? 'success' : 'danger'" size="small" class="status-tag">
            {{ connected ? '已连接' : '未连接' }}
          </el-tag>
        </div>
      </template>
      
      <el-form label-width="80px" class="connection-form" :model="form">
        <el-form-item label="地址">
          <el-input 
            v-model="form.host" 
            placeholder="broker.hivemq.com"
            size="large"
            clearable
          />
        </el-form-item>
        <el-form-item label="端口">
          <el-input-number 
            v-model="form.port" 
            :min="1" 
            :max="65535"
            size="large"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="ClientID">
          <el-input 
            v-model="form.clientId" 
            placeholder="自动生成"
            size="large"
            clearable
          />
        </el-form-item>
      
      <!-- 加密配置 -->
      <el-form-item label="加密">
        <div class="encryption-toggle">
          <el-switch 
            v-model="form.secure" 
            @change="toggleSecure"
            active-color="#409eff"
            inactive-color="#dcdfe6"
          />
          <div class="encryption-info">
            <span class="encryption-text">
              {{ form.secure ? 'SSL/TLS 加密' : '普通连接' }}
            </span>
            <span class="port-info">
              (端口: {{ form.port }})
            </span>
          </div>
        </div>
      </el-form-item>

      <!-- TLS证书配置 -->
      <div v-if="form.secure" class="tls-config-container">
        <el-card shadow="never" class="tls-card">
          <template #header>
            <div class="tls-header">
              <span class="tls-title">TLS证书配置</span>
              <el-tag :type="getCertStatus().type" size="small">
                {{ getCertStatus().text }}
              </el-tag>
            </div>
          </template>
          
          <!-- CA证书 -->
          <el-form-item label="CA证书" class="cert-item">
            <div class="cert-actions">
              <input 
                type="file" 
                accept=".pem,.crt,.cer"
                @change="handleCertUpload('ca', $event)"
                style="display: none"
                ref="caFileInput"
              />
              <el-button 
                size="small" 
                @click="$refs.caFileInput.click()"
                :disabled="!!form.ca"
                class="cert-btn"
              >
                {{ form.ca ? '重新选择' : '选择CA证书' }}
              </el-button>
              <el-button 
                v-if="form.ca" 
                size="small" 
                type="danger" 
                @click="clearCert('ca')"
                class="cert-btn"
              >
                清除
              </el-button>
              <span v-if="form.ca" class="cert-status success">
                ✓ CA证书已配置
              </span>
            </div>
          </el-form-item>

          <!-- 客户端证书 -->
          <el-form-item label="客户端证书" class="cert-item">
            <div class="cert-actions">
              <input 
                type="file" 
                accept=".pem,.crt,.cer"
                @change="handleCertUpload('cert', $event)"
                style="display: none"
                ref="certFileInput"
              />
              <el-button 
                size="small" 
                @click="$refs.certFileInput.click()"
                :disabled="!!form.cert"
                class="cert-btn"
              >
                {{ form.cert ? '重新选择' : '选择客户端证书' }}
              </el-button>
              <el-button 
                v-if="form.cert" 
                size="small" 
                type="danger" 
                @click="clearCert('cert')"
                class="cert-btn"
              >
                清除
              </el-button>
              <span v-if="form.cert" class="cert-status success">
                ✓ 客户端证书已配置
              </span>
            </div>
          </el-form-item>

          <!-- 客户端私钥 -->
          <el-form-item label="客户端私钥" class="cert-item">
            <div class="cert-actions">
              <input 
                type="file" 
                accept=".pem,.key"
                @change="handleCertUpload('key', $event)"
                style="display: none"
                ref="keyFileInput"
              />
              <el-button 
                size="small" 
                @click="$refs.keyFileInput.click()"
                :disabled="!!form.key"
                class="cert-btn"
              >
                {{ form.key ? '重新选择' : '选择私钥文件' }}
              </el-button>
              <el-button 
                v-if="form.key" 
                size="small" 
                type="danger" 
                @click="clearCert('key')"
                class="cert-btn"
              >
                清除
              </el-button>
              <span v-if="form.key" class="cert-status success">
                ✓ 私钥已配置
              </span>
            </div>
          </el-form-item>

          <!-- 证书验证模式 -->
          <el-form-item label="证书验证" class="cert-item">
            <div class="verification-mode">
              <el-switch 
                v-model="form.rejectUnauthorized"
                active-text="严格模式"
                inactive-text="宽松模式"
                active-color="#f56c6c"
                inactive-color="#409eff"
              />
              <span class="verification-text">
                {{ form.rejectUnauthorized ? '严格验证服务器证书' : '跳过证书验证' }}
              </span>
            </div>
            <div class="verification-tip">
              <el-alert
                :title="form.rejectUnauthorized ? '严格模式：验证服务器证书，更安全' : '宽松模式：跳过证书验证，兼容性更好'"
                :type="form.rejectUnauthorized ? 'warning' : 'info'"
                :closable="false"
                show-icon
                effect="dark"
                class="alert-tip"
              />
            </div>
          </el-form-item>

        </el-card>
      </div>
      
        <div class="action-buttons">
          <div class="button-group">
            <el-button
              type="primary"
              :loading="loading"
              :disabled="connected"
              @click="connect"
              size="large"
              class="connect-btn"
              :class="{ 'pulse-effect': connected }"
            >
              <i class="el-icon-connection"></i>
              连接
            </el-button>
            <el-button
              type="danger"
              :disabled="!connected"
              @click="disconnect"
              size="large"
              class="disconnect-btn"
            >
              <i class="el-icon-close"></i>
              断开
            </el-button>
          </div>
        </div>
      </el-form>
    </el-card>

    <!-- 连接状态卡片 -->
    <el-card shadow="never" class="status-card">
      <template #header>
        <div class="card-header">
          <span>连接状态</span>
          <el-button 
            size="small" 
            @click="async()=>{const s=await axios.get('/api/status');ElMessage.info(JSON.stringify(s.data))}"
            class="detail-btn"
          >
            查看详情
          </el-button>
        </div>
      </template>
      
      <!-- SSL状态显示 -->
      <div v-if="form.secure" class="ssl-status-container">
        <el-alert
          title="SSL/TLS 加密连接已启用"
          type="success"
          :closable="false"
          show-icon
          class="ssl-alert"
        >
          <template #default>
            <div class="ssl-details">
              <p>• 连接端口: {{ form.port }} (SSL/TLS加密)</p>
              <p>• 数据传输已加密保护</p>
              <p>• 证书验证: {{ form.rejectUnauthorized ? '严格模式' : '宽松模式' }}</p>
              <div v-if="form.ca || form.cert || form.key" class="cert-summary">
                <p>• 证书配置:</p>
                <ul class="cert-list">
                  <li v-if="form.ca">✓ CA证书已配置</li>
                  <li v-if="form.cert">✓ 客户端证书已配置</li>
                  <li v-if="form.key">✓ 客户端私钥已配置</li>
                </ul>
              </div>
            </div>
          </template>
        </el-alert>
      </div>
      
      <!-- 普通连接状态显示 -->
      <div v-else class="normal-status-container">
        <el-alert
          title="普通MQTT连接"
          type="info"
          :closable="false"
          show-icon
          class="normal-alert"
        >
          <template #default>
            <div class="normal-details">
              <p>• 连接端口: {{ form.port }} (普通连接)</p>
              <p>• {{ connected ? '连接正常' : '尚未连接' }}</p>
            </div>
          </template>
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.connection-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: calc(100vh - 200px);
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.status-tag {
  min-width: 60px;
  text-align: center;
}

.connection-form {
  margin-bottom: 0;
}

.action-buttons {
  margin-bottom: 0;
}

.button-group {
  display: flex;
  gap: 12px;
  width: 100%;
  margin-top: 10px;
}

.connect-btn,
.disconnect-btn {
  flex: 1;
  min-height: 48px;
  font-weight: 500;
  letter-spacing: 0.5px;
  transition: all 0.3s ease;
}

.connect-btn:active,
.disconnect-btn:active {
  transform: scale(0.98);
}

.status-card {
  margin-top: 0;
}

.detail-btn {
  font-size: 12px;
  padding: 4px 12px;
}

/* 加密切换样式 */
.encryption-toggle {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.encryption-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.encryption-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.port-info {
  font-size: 12px;
  color: #909399;
}

/* TLS配置容器 */
.tls-config-container {
  margin-top: 16px;
  margin-left: 0;
}

.tls-card {
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  overflow: hidden;
}

.tls-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tls-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

/* 证书项目样式 */
.cert-item {
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cert-item:last-of-type {
  border-bottom: none;
  margin-bottom: 0;
}

.cert-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.cert-btn {
  font-size: 14px;
  padding: 4px 12px;
  height: 32px;
  white-space: nowrap;
}

.cert-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #f0f9eb;
  font-weight: 500;
}

.cert-status.success {
  color: #67c23a;
}

/* 验证模式样式 */
.verification-mode {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.verification-text {
  font-size: 12px;
  color: #606266;
  flex: 1;
}

.verification-tip {
  margin-top: 8px;
}

.alert-tip {
  font-size: 12px;
  padding: 8px 12px;
  border-radius: 6px;
}

/* SSL状态容器 */
.ssl-status-container,
.normal-status-container {
  margin-top: 12px;
}

.ssl-alert,
.normal-alert {
  border-radius: 8px;
  overflow: hidden;
}

.ssl-details,
.normal-details {
  font-size: 13px;
  line-height: 1.8;
}

.cert-summary {
  margin-top: 8px;
}

.cert-list {
  margin: 6px 0;
  padding-left: 20px;
  list-style-position: inside;
}

.cert-list li {
  font-size: 12px;
  line-height: 1.6;
  color: #606266;
}

/* 脉冲效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

.pulse-effect {
  animation: pulse 2s infinite;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .connection-page {
    gap: 12px;
    padding-bottom: 20px; /* 为底部导航留出更多空间 */
  }
  
  .connection-form :deep(.el-form-item) {
    margin-bottom: 24px;
  }
  
  .connection-form :deep(.el-form-item__label) {
    font-size: 16px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 8px;
    display: block;
  }
  
  .connection-form :deep(.el-input__inner) {
    min-height: 50px;
    font-size: 16px;
    padding: 0 16px;
  }
  
  .connection-form :deep(.el-input-number) {
    width: 100%;
  }
  
  .connection-form :deep(.el-input-number .el-input__inner) {
    min-height: 50px;
    font-size: 16px;
  }
  
  .button-group {
    flex-direction: column;
    gap: 16px;
  }
  
  .connect-btn,
  .disconnect-btn {
    width: 100%;
    min-height: 56px;
    font-size: 18px;
    font-weight: 600;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-header .el-button {
    align-self: flex-end;
  }
  
  .app-title {
    font-size: 20px;
    font-weight: 600;
  }
  
  /* 移动端特定的加密配置样式 */
  .tls-config-container {
    margin-left: 0;
  }
  
  .encryption-toggle {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .encryption-info {
    align-items: center;
    text-align: center;
  }
  
  .encryption-text {
    font-size: 16px;
  }
  
  .port-info {
    font-size: 14px;
  }
  
  /* 证书按钮适配 */
  .cert-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .cert-btn {
    width: 100%;
    margin-bottom: 4px;
  }
  
  .cert-status {
    text-align: center;
    width: 100%;
  }
  
  /* 验证模式适配 */
  .verification-mode {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .verification-text {
    text-align: center;
  }
  
  /* 警报提示适配 */
  .ssl-details,
  .normal-details {
    font-size: 14px;
    line-height: 2.0;
  }
  
  .cert-list {
    padding-left: 16px;
  }
  
  .cert-list li {
    font-size: 13px;
  }
  
  /* 表单元素触摸区域优化 */
  .connection-form :deep(.el-switch) {
    transform: scale(1.3);
    margin: 0 auto;
    display: block;
  }
}

/* 桌面端优化 */
@media (min-width: 769px) {
  .button-group {
    justify-content: center;
    max-width: 400px;
    margin: 20px auto 0;
  }
  
  .connect-btn,
  .disconnect-btn {
    min-width: 140px;
    font-size: 16px;
  }
}

/* 通用样式优化 */
:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

:deep(.el-card__body) {
  padding: 20px;
  background-color: white;
}

:deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
}

:deep(.el-switch) {
  margin-right: 0;
}

:deep(.el-alert) {
  border-radius: 8px;
}

:deep(.el-alert__title) {
  font-weight: 600;
  font-size: 14px;
}

/* 高DPI屏幕优化 */
@media (-webkit-min-device-pixel-ratio: 2) {
  .cert-item {
    border-bottom: 0.5px solid #f0f0f0;
  }
}

/* 移除深色模式适配，保持白色背景 */
</style>


